package com.suns.commom;

import com.suns.exception.ParamException;
import com.suns.exception.PermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//全局异常处理类
//加入日志
@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //获取http request请求的url地址
        String url=request.getRequestURL().toString();
        //返回ModelAndView
        ModelAndView mv;
        //默认的异常msg
        String defaultMsg="System error";

        //判断请求的方式  1.看title  2.看请求的后缀
        // .json   .page
        //这里要求项目中所有请求json数据，都是用.json结尾
        if(url.endsWith(".json")){
            //判断哪些异常是需要特殊处理
            if(ex instanceof PermissionException || ex instanceof ParamException){
                JsonData result=JsonData.fail(ex.getMessage());
                mv=new ModelAndView("jsonView",result.toMap());
            }else {
                //未知异常
                log.error("unknown json exception ,url :" + url,ex);
                JsonData result=JsonData.fail(defaultMsg);
                mv=new ModelAndView("jsonView",result.toMap());
            }
        }else if (url.endsWith(".page")){//这里要求项目中所有请求page页面，都使用.page结尾
            log.error("unknown page exception ,url :" + url,ex);
            JsonData result=JsonData.fail(defaultMsg);
            mv=new ModelAndView("exception",result.toMap());
        }else {
            log.error("unknown exception ,url :" + url,ex);
            JsonData result=JsonData.fail(defaultMsg);
            mv=new ModelAndView("jsonView",result.toMap());
        }

        return mv;
    }
}
